﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;

namespace Phone7ActionPack
{
    public static class Extensions
    {
        /// <summary>
        /// this method will walk up the visual tree from the FrameworkElement that it is called on till 
        /// it finds an object that impliments the supplied type or runs out of tree to walk and returns null
        /// </summary>
        /// <typeparam name="T">the type to </typeparam>
        /// <param name="de"></param>
        /// <returns></returns>
        public static T WalkUpTreeTillType<T>(this FrameworkElement obj) where T : class
        {
            FrameworkElement parent = obj;
            while (parent != null)
            {
                T fe = parent as T;
                if (fe != null)
                    return fe;
                FrameworkElement oldParent = parent;
                parent = VisualTreeHelper.GetParent(parent) as FrameworkElement;

                // Accounts for Popups.
                if (parent == null)
                {
                    parent = oldParent.Parent as FrameworkElement;
                }
            }
            return null;
        }

        /// <summary>
        /// this will perform a command delayed by x miliseconds supplying the object that this is called from as the argument
        /// to the action
        /// </summary>
        /// <typeparam name="T">argument type that will be used for the action</typeparam>
        /// <param name="args">argument that will be passed to the action</param>
        /// <param name="action">the action that will be called</param>
        /// <param name="msDelay">number of ms to dely this command </param>
        public static void DelayedCommand<T>(this T args, Action<T> action, int msDelay)
        {
            System.Windows.Threading.DispatcherTimer timer = new System.Windows.Threading.DispatcherTimer();
            timer.Tick += (s, e) =>
            {
                action.Invoke(args);
                timer.Stop();
            };
            timer.Interval = new TimeSpan(0, 0, 0, 0, msDelay);
            timer.Start();
        }
    }
}